<template>
    <div style="display: flex">
        <el-button type="primary" style="margin-right: 15px" @click="addItem">新增</el-button>
        <el-select v-model="searchCourseId" placeholder="请选择课程名称" filterable clearable
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px">
            <el-option v-for="item in courseOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-select v-model="searchTeachId" placeholder="请选择培训讲师" filterable clearable
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px">
            <el-option v-for="item in teacherOptions" :key="item.id" :label="item.username"
                :value="item.id"></el-option>
        </el-select>
        <el-select v-model="searchFlow" placeholder="请选择微课状态" clearable
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px">
            <el-option v-for="item in flowOptions" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
        </el-select>
        <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
        </el-button>
    </div>

    <el-table :data="tableData" :row-style="{ height: '77px' }" border
        style="width: calc(100vw - 240px);height: 75vh;margin-top: 20px;font-size: 15px;">
        <el-table-column align="center" prop="name" label="微课名称" width="250" />
        <el-table-column align="center" prop="courseName" label="课程名称" width="250" />
        <el-table-column align="center" prop="teachName" label="培训讲师名称" width="150" />
        <el-table-column align="center" prop="flow" label="微课状态" width="150">
            <template #default="scope">
                <el-tag type="success" v-if="scope.row.flow === 0">准备中</el-tag>
                <el-tag type="success" v-else-if="scope.row.flow === 1">开讲中</el-tag>
                <el-tag type="success" v-else-if="scope.row.flow === 2">已结束</el-tag>
            </template>
        </el-table-column>
        <el-table-column align="center" prop="url" label="微课路径" width="auto" />
        <el-table-column align="center" prop="startTime" label="开始时间" width="auto" />
        <el-table-column align="center" prop="endTime" label="结束时间" width="auto" />
        <el-table-column align="center" fixed="right" label="操作" width="200">
            <template v-slot="scope">
                <div>
                    <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
                </div>
                <div>
                    <el-button v-if="scope.row.flow !== 1" type="success" size="small" icon="VideoPause"
                        @click="updateFlow(scope.row, 1)">开启微课
                    </el-button>
                    <el-button v-if="scope.row.flow === 1" type="Delete" size="small" icon="VideoPause"
                        @click="updateFlow(scope.row, 2)">结束微课
                    </el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div style="margin-top: 10px">
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" :background="true"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-model="dialogVisible" title="微课操作" width="500" @close="reset('form')">
        <el-form label-position="top" :model="form" ref="form" :rules="rules">
            <el-form-item label="微课名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入微课名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="课程名称" prop="courseId">
                <el-select v-model="form.courseId" placeholder="请选择课程名称" filterable clearable>
                    <el-option v-for="course in courseOptions" :key="course.id" :label="course.name"
                        :value="course.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="培训讲师名称" prop="teachId">
                <el-select v-model="form.teachId" placeholder="请选择培训讲师名称" style="width: 100%" filterable clearable>
                    <el-option v-for="item in teacherOptions" :key="item.id" :label="item.username"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="微课路径" prop="url">
                <el-input v-model="form.url" placeholder="请输入微课路径" clearable></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reset('form')">取消</el-button>
                <el-button type="primary" @click="submitForm('form')">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--<el-dialog :close-on-click-modal="false" title="微课画面" v-model="liveDialogVisible" width="70%"-->
    <!--@close="stopStreaming">-->
    <!--<el-form label-position="left" :inline="true">-->
    <!--<el-form-item label="摄像头">-->
    <!--<el-select v-model="selectedCamera" placeholder="选择摄像头" @change="changeCamera" style="width: 300px">-->
    <!--<el-option v-for="camera in cameras" :key="camera.deviceId" :label="camera.label || '摄像头'"-->
    <!--:value="camera.deviceId" />-->
    <!--</el-select>-->
    <!--</el-form-item>-->
    <!--<el-form-item label="麦克风">-->
    <!--<el-select v-model="selectedAudio" placeholder="选择麦克风" @change="changeAudio" style="width: 300px">-->
    <!--<el-option v-for="audio in audios" :key="audio.deviceId" :label="audio.label || '麦克风'"-->
    <!--:value="audio.deviceId" />-->
    <!--</el-select>-->
    <!--<el-button icon="Refresh" @click="refreshDevices" style="margin-left: 15px;width: 100px">刷新设备-->
    <!--</el-button>-->
    <!--</el-form-item>-->
    <!--</el-form>-->
    <!--<video ref="videoElement" autoplay muted playsinline></video>-->
    <!--<template #footer>-->
    <!--<div class="dialog-footer">-->
    <!--<el-button :disabled="isStreaming" @click="startStreaming" type="primary">开始微课</el-button>-->
    <!--<el-button :disabled="!isStreaming" @click="stopStreaming">停止微课</el-button>-->
    <!--</div>-->
    <!--</template>-->
    <!--</el-dialog>-->
</template>

<script>

import { ref } from 'vue'
import request from "~/utils/request.js";
import { getToken } from "../../composables/auth";

export default {
    data() {
        return {
            dialogVisible: false,
            tableData: [],
            form: {},
            courseOptions: [],
            teacherOptions: [],
            flowOptions: [
                {
                    value: 0,
                    label: '准备中',
                },
                {
                    value: 1,
                    label: '开讲中',
                },
                {
                    value: 2,
                    label: '已结束',
                }
            ],
            searchCourseId: '',
            searchTeachId: '',
            searchFlow: '',
            searchCourseType: '',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            rules: {
                name: [
                    { required: true, message: '请输入微课名称', trigger: 'blur' },
                ],
                teachId: [
                    { required: true, message: '请选择培训讲师名称', trigger: 'blur' },
                ],
                courseId: [
                    { required: true, message: '请选择课程名称', trigger: 'blur' },
                ],
                url: [
                    { required: true, message: '请输入微课路径', trigger: 'blur' },
                ],
            },
            //微课参数
            live: {},
            liveDialogVisible: false,
            videoElement: null,
            stream: null,
            socket: null,
            isStreaming: false,
            cameras: [],
            selectedCamera: '',
            audios: [],
            selectedAudio: ''
        }
    },
    // mounted() {
    //     this.refreshDevices();
    // },
    async created() {
        await this.getCourseOptions()
        await this.getTeacherOptions()
        await this.load()
    },
    // beforeDestroy() {
    //     this.stopStreaming();
    // },
    methods: {
        async load() {
            if (this.searchCourseId === undefined) {
                this.searchCourseId = ''
            }
            if (this.searchTeachId === undefined) {
                this.searchTeachId = ''
            }
            if (this.searchFlow === undefined) {
                this.searchFlow = ''
            }
            request.get("/live/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&courseId=" + this.searchCourseId + "&flow=" + this.searchFlow + "&teachId=" + this.searchTeachId).then(res => {
                if (res.code === '200') {
                    this.tableData = res.data.records
                    this.total = res.data.total
                } else {
                    ElMessage.error("错误" + res.msg)
                }
            })
        },
        async getCourseOptions() {
            request.get("/course/all").then(res => {
                this.courseOptions = res.data
            })
        },
        async getTeacherOptions() {
            request.get("/user/selectTeachers").then(res => {
                this.teacherOptions = res.data
            })
        },
        editItem(item) {
            Object.assign(this.form, item)
            this.dialogVisible = true
        },
        addItem() {
            this.dialogVisible = true;
        },
        // 删除
        deleteItem(scope) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/live/delete/" + scope).then(res => {
                    if (res.code === '200') {
                        this.$message.success("成功")
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            });
        },
        // 提交
        submitForm(val) {
            this.$refs[val].validate((valid) => {
                if (valid) {
                    request.post("/live/edit", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message({
                                message: "成功",
                                type: "success"
                            })
                            this.load()
                            this.reset(val)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        },
        // 取消
        reset(val) {
            this.dialogVisible = false;
            this.form = {};
            this.$refs[val].resetFields();
        },
        handleCurrentChange(item) {
            // 改变当前页码触发
            this.currentPage = item
            this.load()
        },
        handleSizeChange(item) {   // 改变当前每页的个数触发
            this.pageSize = item
            this.load()
        },

        //微课
        // async refreshDevices() {
        //     try {
        //         // 请求基础权限
        //         await navigator.mediaDevices.getUserMedia({
        //             video: true,
        //             audio: true
        //         });
        //
        //         // 获取设备列表
        //         const devices = await navigator.mediaDevices.enumerateDevices();
        //
        //         this.cameras = devices
        //             .filter(d => d.kind === 'videoinput')
        //             .map(d => ({
        //                 deviceId: d.deviceId,
        //                 label: d.label || `摄像头 ${this.cameras.length + 1}`
        //             }));
        //
        //         this.audios = devices
        //             .filter(d => d.kind === 'audioinput')
        //             .map(d => ({
        //                 deviceId: d.deviceId,
        //                 label: d.label || `麦克风 ${this.audios.length + 1}`
        //             }));
        //
        //         if (this.cameras.length > 0 && !this.selectedCamera) {
        //             this.selectedCamera = this.cameras[0].deviceId;
        //         }
        //         if (this.audios.length > 0 && !this.selectedAudio) {
        //             this.selectedAudio = this.audios[0].deviceId;
        //         }
        //
        //     } catch (error) {
        //         console.error('设备获取失败:', error);
        //         this.$message.error('无法访问设备，请检查权限设置');
        //     }
        // },

        // async changeCamera() {
        //     if (this.isStreaming) {
        //         await this.stopStreaming(this.liveId);
        //         await this.startStreaming(this.liveId);
        //     }
        // },

        // async changeAudio() {
        //     if (this.isStreaming) {
        //         await this.stopStreaming(this.liveId);
        //         await this.startStreaming(this.liveId);
        //     }
        // },
        updateFlow(item, flow) {
            // 在开始前确保弹窗已打开
            // this.liveDialogVisible = true;
            // this.live = item
            // this.refreshDevices();
            request.get("/live/updateFlow?id=" + item.id + "&flow=" + flow).then(res => {
                if (res.code === '200') {
                    this.$message.success("开启成功")
                    this.load()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        // async startStreaming() {
        //     this.live.flow = 1
        //
        //     try {
        //         const res = await request.get("/live/startStreaming?id=" + this.live.id)
        //         if (res.code === '200') {
        //             this.$message.success("微课开始")
        //         } else if (res.code === '201') {
        //             this.$message.error(res.msg)
        //             return;
        //         } else {
        //             this.$message.error(res.msg)
        //             return;
        //         }
        //         // 获取媒体流
        //         this.stream = await navigator.mediaDevices.getUserMedia({
        //             video: {
        //                 deviceId: this.selectedCamera
        //                     ? { exact: this.selectedCamera }
        //                     : undefined
        //             },
        //             audio: {
        //                 deviceId: this.selectedAudio
        //                     ? { exact: this.selectedAudio }
        //                     : undefined
        //             }
        //         });
        //         // 增加延迟确保DOM加载完成
        //         this.$nextTick(() => {
        //             this.$refs.videoElement.srcObject = this.stream;
        //         });
        //
        //         this.socket = new WebSocket('ws://172.16.1.228:9100/api/live/' + this.live.id, [], {
        //             headers: {
        //                 "Authorization": getToken()
        //             }
        //         });
        //
        //         this.socket.onopen = () => {
        //             console.log('WebSocket连接已建立');
        //             this.isStreaming = true;
        //
        //             const supportedMimeTypes = [
        //                 'video/webm; codecs=vp9,opus',
        //                 'video/webm; codecs=vp8,opus',
        //                 'video/webm; codecs=h264,opus',
        //                 'video/webm'
        //             ];
        //
        //             let selectedMimeType = null;
        //             for (const mimeType of supportedMimeTypes) {
        //                 if (MediaRecorder.isTypeSupported(mimeType)) {
        //                     selectedMimeType = mimeType;
        //                     break;
        //                 }
        //             }
        //
        //             if (!selectedMimeType) {
        //                 console.error('没有找到支持的编码格式');
        //                 return;
        //             }
        //
        //             const mediaRecorder = new MediaRecorder(this.stream, {
        //                 mimeType: selectedMimeType
        //             });
        //
        //             mediaRecorder.ondataavailable = (event) => {
        //                 if (event.data.size > 0 && this.isStreaming) {
        //                     this.socket.send(event.data);
        //                 }
        //             };
        //
        //             mediaRecorder.start(100);
        //         };
        //
        //         this.socket.onclose = () => {
        //             console.log('WebSocket连接已关闭');
        //             this.isStreaming = false;
        //         };
        //
        //         this.socket.onerror = (error) => {
        //             console.error('WebSocket连接出错:', error);
        //             this.isStreaming = false;
        //         };
        //
        //     } catch (error) {
        //         console.error('获取媒体流失败:', error);
        //         this.liveDialogVisible = false;
        //     }
        //
        // },
        // stopStreaming() {
        //     // 确保在任何情况下都释放媒体资源
        //     if (this.stream) {
        //         this.stream.getTracks().forEach(track => {
        //             track.stop(); // 停止所有媒体轨道
        //             track.enabled = false; // 禁用轨道
        //         });
        //         this.stream = null; // 清除流引用
        //     }
        //
        //     // 关闭WebSocket连接
        //     if (this.socket) {
        //         this.socket.close();
        //         this.socket = null;
        //     }
        //
        //     // 更新微课状态
        //     if (this.live.flow === 1) {
        //         request.get("/live/stopStreaming?id=" + this.live.id).then(res => {
        //             if (res.code === '200') {
        //                 this.$message.success("微课结束")
        //                 this.isStreaming = false;
        //                 this.load(); // 刷新列表
        //             } else {
        //                 this.$message.error(res.msg)
        //             }
        //         })
        //     }
        //
        //     // 关闭弹窗
        //     this.liveDialogVisible = false;
        // }
    }
}

</script>

<style scoped>
.device-selectors {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    align-items: center;
}

video {
    width: 100%;
    height: 500px;
    background: #000;
    border-radius: 4px;
}
</style>
